package com.panopset.io;

import java.io.File;
import java.io.StringWriter;

public final class GlobalReplace extends DirectoryProcessor {
    private final String from;
    private final String to;
    private final String ext;
    
    /**
     *
     * @param dir
     * @param from
     * @param to
     * @param extension
     */
    GlobalReplace(File dir, String from, String to, String extension) {
        super(dir);
        this.from = from;
        this.to = to;
        this.ext = extension;
    }

    @Override
    protected void process(File f) {
        if (com.panopset.Util.getExtension(f).equals(ext)) {
            final StringWriter sw = new StringWriter();
            new FileProcessor.Builder().file(f).listener(new FileProcessor.Listener() {
                
                @Override
                public void process(FileProcessor processor, String[] values) {
                    for (String s : values) {
                        sw.append(s.replace(from, to));
                        sw.append(com.panopset.Util.getEol());
                    }
                }
                
                @Override
                public void finish(FileProcessor processor) {
                    // nothing to do here.
                }
                
            }).construct().exec();
            com.panopset.Util.saveStringToFile(sw.toString(), f);
        }
    }

}
